import {
  generateHtmlContent,
  generateIconfontContent,
  generateSymbolContnt,
} from "./templates";
import { getIconfontContent, getOutputPath } from "./tools";
import { IOptions, ISvgOptions } from "./types";
const fs = require("fs");
const path = require("path");

export function removeSvgs(options: IOptions) {
  options.outputValue = options.outputValue || options.inputValue;
  const { inputValue = "", remove } = options;
  if (!remove || typeof remove !== "string") {
    throw new Error("remove should be a string");
  }
  const inputPath = path.join(
    process.cwd(),
    ...inputValue.split("/").filter(Boolean)
  );
  if (!fs.statSync(inputPath).isFile() && !inputValue.endsWith(".js")) {
    throw new Error("input should be a .js file");
  }
  const { svgId, svgList: oldSvgList } = getIconfontContent(inputPath);
  const removeMap = remove
    .split(",")
    .filter(Boolean)
    .reduce((p, id) => {
      p[id] = true;
      return p;
    }, {} as any);
  outputFile(
    svgId,
    oldSvgList.filter((svg) => !removeMap[svg.name]),
    options
  );
}

// 输出iconfont.js文件
function outputFile(svgId: string, svgList: ISvgOptions[], options: IOptions) {
  const { outputValue } = options;
  const outputPath = getOutputPath(outputValue, "iconfont.js", ".js");
  const content = generateIconfontContent(
    svgList.map(generateSymbolContnt).join(""),
    svgId
  );
  fs.writeFileSync(outputPath, content);
  const html = generateHtmlContent(svgList.map((item) => item.name));
  const htmlPath = path.join(path.parse(outputPath).dir, "index.html");
  fs.writeFileSync(htmlPath, html);
}
